package com.bitdf.txing.users.controller;

import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.users.constant.CommonConstant;
import com.bitdf.txing.users.feign.ThirdPartFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("${txing.request.path.users}")
public class LoginRegistController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    /**
     * 发送验证码
     * @param phone  手机号码
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendcode(@RequestParam("phone") String phone){
        String redisCode = redisTemplate.opsForValue().get(CommonConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode))
        {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis()-l<60000)
            {
                return R.error(TxCodeEnume.COMMON_SMS_CODE_EXCEPTION);
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = code+"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(CommonConstant.SMS_CODE_CACHE_PREFIX+phone, substring,5, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }
}
